package com.api_gateway.filter;

import com.api_gateway.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;

import java.nio.charset.StandardCharsets;

// 简化的全局过滤器，仅用于日志记录等基础功能
@Component
@Slf4j
@Order(0)
public class AuthGlobalFilter implements WebFilter, Ordered {
    
    private final JwtUtil jwtUtil;
    
    public AuthGlobalFilter(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().value();

        log.debug("Request path: {}", path);
        
        // 在filter方法中添加头传递逻辑
        ServerHttpRequest newRequest = request.mutate()
            .header("user-id", "123") // 测试时硬编码，实际应从JWT解析
            .build();
        return chain.filter(exchange.mutate().request(newRequest).build());
    }

    @Override
    public int getOrder() {
        return 0; // 过滤器执行顺序，数值越小优先级越高
    }
}